/* model */
import RootWindowInitData from '@model/interface/initData/RootWindowInitData';
import LoginUser from '@model/entity/LoginUser/LoginUser';
/* util */
import Log from '@src/util/log.ts';
import { getRootWindow } from '@src/util/dom';

/**
 * @description: 获取顶层窗口数据
 * @return {RootWindowInitData} 数据
 */
export function getRootWindowInitData(): RootWindowInitData {
  try {
    const RootWindow: any = getRootWindow(window);
    if (RootWindow._init) {
      return JSON.parse(RootWindow._init);
    } else {
      return {};
    }
  } catch (error) {
    Log.error(error, getRootWindowInitData.name);
    return {} as RootWindowInitData;
  }
}

export function setRootWindowInitData(data: any) {
  try {
    const RootWindow: any = getRootWindow(window);
    RootWindow._init = JSON.stringify(data);
  } catch (error) {
    Log.error(error, getRootWindowInitData.name);
    return data;
  }
}

export function getRootWindowInitDataUser() {
  const data = getRootWindowInitData();
  return data?.user || ({} as LoginUser);
}

export function getRootWindowInitDataUserRoles() {
  const user = getRootWindowInitDataUser();
  return user?.roles || [];
}
/**
 * @description 过滤xss
 * @param str 
 * @returns 
 */
export function filterXss(str: string): string {
  if (!str) return '';
  str = str.replaceAll(/&/g, '&amp;');
  str = str.replaceAll(/</g, '&lt;');
  str = str.replaceAll(/>/g, '&gt;');
  str = str.replaceAll(/"/g, '&quto;');
  str = str.replaceAll(/'/g, '&#39;');
  return str;
}
export default {
  getRootWindowInitData,
  setRootWindowInitData,
};
